using System;
using UnityEngine;
using QFramework;
using Random = UnityEngine.Random;

namespace Survivor
{
	public partial class CameraCrontroller : ViewController
	{
		private static CameraCrontroller instance;
		
		private Vector2 targetPos = Vector2.zero;

		private float followSpeed = 10f;

		private Vector3 curPos = Vector3.zero;

		private static bool isShake;
		private static int shakeFrame;
		private float shakeStrength = 0.2f;

		private void Start()
		{
			instance = this;
		}

		public static void PlayShake()
		{
			isShake = true;
			shakeFrame = 30;
		}

		private void Update()
		{
			if (Player.Instance == null)
				return;

			targetPos = Player.Instance.transform.position;
			var position = transform.position;
			curPos.x = Mathf.Lerp(position.x, targetPos.x, 1.0f - Mathf.Exp(-Time.deltaTime * followSpeed));
			curPos.y = Mathf.Lerp(position.y, targetPos.y, 1.0f - Mathf.Exp(-Time.deltaTime * followSpeed));
			curPos.z = position.z;

			if (isShake)
			{
				shakeFrame--;
				float strength = Mathf.Lerp(shakeStrength, 0, shakeFrame / 30f);
				transform.position = new Vector3(curPos.x + Random.Range(-strength, strength),
					curPos.y + Random.Range(-strength, strength), curPos.z);
				if (shakeFrame <= 0)
				{
					isShake = false;
				}
			}
			else
			{
				transform.PositionX(curPos.x);
				transform.PositionY(curPos.y);
			}
			
			
		}
	}
}
